'use strict';
const dayjs = require("dayjs");
const {getDefaultModelConfig} = require("../../utils/common");
const {formatDate} = require("../../utils");

module.exports = app => {
    const { STRING, INTEGER, BIGINT, DATE, TINYINT } = app.Sequelize;
    const UserCoupon = app.model.define(
        'UserCoupon',
        {
            id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true },
            user_id: { type: BIGINT.UNSIGNED, allowNull: false },
            coupon_id: { type: BIGINT.UNSIGNED, allowNull: false },
            coupon_code: { type: STRING(64), allowNull: false, unique: true },
            status: { type: TINYINT, allowNull: false, defaultValue: 0 },
            order_id: { type: BIGINT.UNSIGNED, allowNull: true },
            use_time: { type: DATE, allowNull: true,
                get() {
                    return formatDate(this.getDataValue('use_time'), 'YYYY-MM-DD HH:mm:ss');
                }
                },
            obtain_time: { type: DATE, allowNull: false,
                get() {
                    return formatDate(this.getDataValue('obtain_time'), 'YYYY-MM-DD HH:mm:ss');
                }
            },
            expire_time: { type: DATE, allowNull: false,
                get() {
                    return formatDate(this.getDataValue('expire_time'), 'YYYY-MM-DD HH:mm:ss');
                }
            },
            creator: { type: BIGINT, allowNull: false, defaultValue: 0 },
            updater: { type: BIGINT, allowNull: false, defaultValue: 0 },
            deleted: { type: TINYINT, allowNull: false, defaultValue: 0 },
            ...getDefaultModelConfig(app)
        },
        {
            tableName: 'user_coupon',
            timestamps: true,
            createdAt: 'create_time',
            updatedAt: 'update_time'
        }
    );
    UserCoupon.associate = function () {
        app.model.Business.UserCoupon.belongsTo(app.model.Business.Coupon, { foreignKey: 'coupon_id', targetKey: 'id', as: 'coupon' });
        app.model.Business.UserCoupon.belongsTo(app.model.Business.User, { foreignKey: 'user_id', targetKey: 'id', as: 'user' });
        app.model.Business.UserCoupon.belongsTo(app.model.Business.Order, { foreignKey: 'order_id', targetKey: 'id', as: 'order' });
    }

    return UserCoupon
};
